from flask import Flask, Blueprint
from flask import render_template, request, jsonify
import zhipuai

sj = Blueprint('sj', __name__, template_folder='ygy_templates', static_folder='ygy_static')
@sj.route('/shanjiu')
def index():
    with open('vilipixiv/ghj/left_plot.html') as f:
        left_plot = f.read()
    with open('vilipixiv/ghj/rigtht_plot.html') as f:
        right_plot = f.read()
    return render_template('shanjiu.html', left_plot=left_plot, right_plot=right_plot)

@sj.route('/api', methods=['POST'])
def sse_invoke_example_from_flask():
    zhipuai.api_key = "45a4d88e7e99efc6c674b383efcc7846.jWYz1kDNEo5hyRWO"
    user_say = request.json.get('user_say')  # 从请求中获取用户输入
    if user_say:
        try:
            response = zhipuai.model_api.sse_invoke(
                model="chatglm_pro",
                prompt=[{"role": "user", "content": user_say}],
                top_p=0.7,
                temperature=0.9,
            )
            data = []
            for event in response.events():
                if event.event == "add":
                    data.append(event.data)
                elif event.event == "error" or event.event == "interrupted":
                    data.append(event.data)
                elif event.event == "finish":
                    data.append(event.data)
                    print(event.meta)
                else:
                    data.append(event.data)
            return jsonify(data)  # 以JSON形式返回结果
        except Exception as e:
            return jsonify({'error': str(e)})  # 如果有异常，返回错误信息
    else:
        return jsonify({'error': 'No user input received.'}), 400  # 如果未收到用户输入，返回错误响应
